﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using Repo.Helpers;

namespace SPRepoDemo.Web.Helpers
{
    public static class DeploymentHelper
    {
        #region Constants

        private const string Masterpagelocation = "/_catalogs/masterpage/";
        private const string DefaultMasterpage = "v4.master";

        #endregion

        public static void SetHomePage(SPWeb web, string page)
        {
            try
            {
                var pubWeb = PublishingWeb.GetPublishingWeb(web);
                var file = pubWeb.Web.GetFile(page);
                pubWeb.DefaultPage = file;
                pubWeb.Update();
            }
            catch (Exception exception)
            {
                LoggingHelper.ErrorLog(exception, "HomePageDeployment");
                throw;
            }
        }

        public static void ApplyMasterPage(SPWeb web, string masterPage)
        {
            ReplaceMasterUrl(web, masterPage);
        }

        public static void ApplyCustomMasterPage(SPWeb web, string masterPage)
        {
            ReplaceCustomMasterUrl(web, masterPage);
        }

        public static void RemoveMasterPage(SPWeb web)
        {
            ReplaceMasterUrl(web, DefaultMasterpage);
        }

        public static void RemoveCustomMasterPage(SPWeb web)
        {
            ReplaceCustomMasterUrl(web, DefaultMasterpage);
        }

        #region private methods

        private static void ReplaceCustomMasterUrl(SPWeb web, string newMaster)
        {
            web.CustomMasterUrl = Masterpagelocation + newMaster;
            web.Update();
        }

        private static void ReplaceMasterUrl(SPWeb web, string newMaster)
        {
            web.MasterUrl = Masterpagelocation + newMaster;
            web.Update();
        }

        #endregion
    }
}
